﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace IEC
{
    //gamepath
    public class GameConfig
    {
        private string SteamGamePath = null;
        public enum ConfigStatus
        {
            Unknown,
            OK
        };
        public GameConfig()
        {
            RefindGamePath();
        }

        public bool RefindGamePath()
        {
            string FindSteamGamePath()
            {
                try
                {
                    // find Steam Path
                    var key = Microsoft.Win32.RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.CurrentUser, Microsoft.Win32.RegistryView.Default);
                    if (key == null)
                        return null;
                    key = key.OpenSubKey(@"SOFTWARE\Valve\Steam", false);
                    if (key == null)
                        return null;
                    var steampath = key.GetValue("SteamPath", null) as string;
                    if (steampath == null)
                        return null;
                    var vdfpath = System.IO.Path.Combine(steampath, "config", "libraryfolders.vdf");
                    dynamic folders = Gameloop.Vdf.VdfConvert.Deserialize(System.IO.File.ReadAllText(vdfpath)).Value;
                    foreach (var folder in folders)
                    {
                        foreach (var app in folder.Value.apps)
                        {
                            var appid = app.Key;
                            if (appid == "250900")
                            {
                                return folder.Value.path.Value;
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    return null;
                }
                return null;
            }
            string CheckGameAndDlcs(string libpath)
            {
                var exepath = System.IO.Path.Combine(libpath, "steamapps", "common", "The Binding of Isaac Rebirth", "isaac-ng.exe");
                if(System.IO.File.Exists(exepath) != true)
                    return "Steam路径下的游戏文件不正确，请检查游戏完整性或手动设置路径。";
                var manifestpath = System.IO.Path.Combine(libpath, "steamapps", "appmanifest_250900.acf");
                if (System.IO.File.Exists(manifestpath) != true)
                    return "未检测到Steam游戏清单文件，请检查游戏完整性或手动设置路径。";
                try
                {
                    bool afterbirth = false, afterbirthplus = false, repentance = false;
                    dynamic manifest = Gameloop.Vdf.VdfConvert.Deserialize(System.IO.File.ReadAllText(manifestpath)).Value;
                    foreach(var depot in manifest.InstalledDepots)
                    {
                        var dlcappid = depot.Value.dlcappid;
                        if(dlcappid != null)
                        {
                            if (dlcappid.Value == "401920")
                                afterbirth = true;
                            if (dlcappid.Value == "570660")
                                afterbirthplus = true;
                            if (dlcappid.Value == "1426300")
                                repentance = true;
                        }

                    }
                    if (!afterbirth)
                        return "此工具仅支持忏悔（检测到您没有安装胎衣DLC，如果检测有误，请手动设置路径。）";
                    if (!afterbirthplus)
                        return "此工具仅支持忏悔（检测到您没有安装胎衣+DLC，如果检测有误，请手动设置路径。）";
                    if (!repentance)
                        return "此工具仅支持忏悔（检测到您没有安装忏悔DLC，如果检测有误，请手动设置路径。）";
                }
                catch (Exception)
                {
                    return "我们无法确保游戏版本正确，请检查游戏完整性或手动设置路径。";
                }
                return null;
            }
            if (MainWindow.myConfig.ReadFromSteam)
            {
                string libpath = FindSteamGamePath();
                if(libpath == null)
                {
                    MessageBox.Show("未找到Steam游戏库路径，请手动设置。");
                }
                string check = CheckGameAndDlcs(libpath);
                if (check != null)
                {
                    MessageBox.Show(check, "提示");
                }
                else
                {
                    SteamGamePath = System.IO.Path.Combine(libpath, "steamapps", "common", "The Binding of Isaac Rebirth");
                    return true;
                }
            }
            return false;
        }


        public ConfigStatus GetStatus()
        {
            if (GetGamePath() == null)
                return ConfigStatus.Unknown;
            return new System.IO.FileInfo(System.IO.Path.Combine(GetGamePath(),"isaac-ng.exe")).Exists ? ConfigStatus.OK : ConfigStatus.Unknown;
        }
        public string GetGamePath()
        {
            if (MainWindow.myConfig.ReadFromSteam)
            {
                return SteamGamePath;
            }
            return MainWindow.myConfig.GamePath;
        }

        public string GetOptionPath()
        {
            if (GetStatus() != ConfigStatus.OK)
                return null;
            string p = System.IO.Path.Combine(GetGamePath(), "savedatapath.txt");
            if (System.IO.File.Exists(p))
            {
                var re = new System.Text.RegularExpressions.Regex("Save Data Path: (.*)");
                foreach (string line in System.IO.File.ReadAllLines(p))
                {
                    var match = re.Match(line.TrimEnd('\n', '\r'));
                    if (match.Success)
                    {
                        string docFolder = match.Groups[1].Value;
                        string optionFile = System.IO.Path.Combine(docFolder, "options.ini");
                        if (System.IO.File.Exists(optionFile))
                            return optionFile;
                    }
                }
            }
            return null;
        }

        public string GetModPath()
        {
            if (GetStatus() != ConfigStatus.OK)
                return null;

            return System.IO.Path.Combine(GetGamePath(), "mods");
        }
        public string GetModWorkshopPath()
        {
            if (GetStatus() != ConfigStatus.OK)
                return null;
            string path = System.IO.Path.Combine(GetGamePath(), "..", "..", "workshop", "content", "250900");
            if (new System.IO.DirectoryInfo(path).Exists)
                return path;
            return null;
        }
        public string GetModDataPath()
        {
            if (GetStatus() != ConfigStatus.OK)
                return null;

            return System.IO.Path.Combine(GetGamePath(), "data");
        }
    }
}
